/**
 * Copyright (C) 2010-2013 Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.rocketmq.example.benchmark;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.message.MessageExt;


/**
 * 性能测试，订阅消息
 */
public class DelayConsumer {
	private static String topic;
	private static int threadCount;
	private static int sleepTime;
	private static AtomicLong totalConsumer = new AtomicLong();

	public static void main(String[] args) throws MQClientException {
		topic = args.length >= 1 ? args[0] : "BenchmarkTest";
		threadCount = args.length >= 2 ? Integer.parseInt(args[1]) : 1;
		sleepTime = args.length >= 3 ? Integer.parseInt(args[2]) : 0;

		initDelayLevel();

		final DelayStatsBenchmarkConsumer statsBenchmarkConsumer = new DelayStatsBenchmarkConsumer();
		final ExecutorService receiveThreadPool = Executors.newFixedThreadPool(threadCount);
        final Timer timer = new Timer("BenchmarkTimerThread", true);

        final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
                if (snapshotList.size() > 10) {
                    snapshotList.removeFirst();
                }
            }
        }, 1000, 1000);

        timer.scheduleAtFixedRate(new TimerTask() {
            private void printStats() {
                if (snapshotList.size() >= 10) {
                    Long[] begin = snapshotList.getFirst();
                    Long[] end = snapshotList.getLast();

                    final long consumeTps =
                            (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                    final double averageB2CRT = ((end[2] - begin[2]) / (double) (end[1] - begin[1]));
                    final double averageS2CRT = ((end[3] - begin[3]) / (double) (end[1] - begin[1]));
					final double avgDelay = ((end[4] - begin[4]) / (double) (end[1] - begin[1]));

                    System.out.printf(
							"Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f AvgDelay: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d\n"//
                        , consumeTps//
                        , averageB2CRT//
                        , averageS2CRT//
							, avgDelay//
                        , end[4]//
                        , end[5]//
							);
					System.out.println("totalConsumer:" + totalConsumer.get());
					;
                }
            }


            @Override
            public void run() {
                try {
                    this.printStats();
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 10000, 10000);

		for (int i = 0; i < threadCount; i++) {
			receiveThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						// + Long.toString(System.currentTimeMillis() % 100)
						DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("benchmark_consumer" + topic);

						// 可以设置批量消费
						// consumer.setConsumeMessageBatchMaxSize(consumeMessageBatchMaxSize);
						consumer.setInstanceName(Long.toString(System.currentTimeMillis()));
						// consumer.setNamesrvAddr("127.0.0.1:9876");
						consumer.subscribe(topic, "*");

						consumer.registerMessageListener(new MessageListenerConcurrently() {
							@Override
							public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
									ConsumeConcurrentlyContext context) {
								MessageExt msg = msgs.get(0);
								/**
								 * 下面的方式可以判断消息的堆积情况
								 */
								// long offset = msgs.get(0).getQueueOffset();
								// String maxOffset = //
								// msgs.get(0).getProperty(MessageConst.PROPERTY_MAX_OFFSET);
								// long diff = Long.parseLong(maxOffset) -
								// offset;
								// if (diff > 100000) {
								// // TODO 消息堆积超过10W条，特殊处理
								// return
								// ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
								// }

								long now = System.currentTimeMillis();
								long clientTime = msg.getBornTimestamp();
								long interval = delayLevelTable.get(msg.getDelayTimeLevel());

								System.out.println(msgs.size() + "," + msg.getKeys() + "," + totalConsumer.get());

								// 1
								statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

								// 2
								long born2ConsumerRT = now - msg.getBornTimestamp();
								statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

								// 3
								long store2ConsumerRT = now - msg.getStoreTimestamp();
								statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

								// 4
								compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

								// 5
								compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

								// 6
								statsBenchmarkConsumer.getDelayTotal().addAndGet(now - clientTime - interval);

								totalConsumer.incrementAndGet();
								if (sleepTime > 0) {
									try {
										Thread.sleep(sleepTime);
									} catch (InterruptedException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}

								return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
							}
						});

						consumer.start();

						System.out.println("Consumer Started.");
					} catch (Exception e) {

					}

				}
			});
		}

    }

	// 每个level对应的延时时间
	private static final ConcurrentHashMap<Integer, Long> delayLevelTable = new ConcurrentHashMap<Integer, Long>(32);

	public static boolean initDelayLevel() {
		HashMap<String, Long> timeUnitTable = new HashMap<String, Long>();
		timeUnitTable.put("s", 1000L);
		timeUnitTable.put("m", 1000L * 60);
		timeUnitTable.put("h", 1000L * 60 * 60);
		timeUnitTable.put("d", 1000L * 60 * 60 * 24);

		String levelString = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
		try {
			String[] levelArray = levelString.split(" ");
			for (int i = 0; i < levelArray.length; i++) {
				String value = levelArray[i];
				String ch = value.substring(value.length() - 1);
				Long tu = timeUnitTable.get(ch);

				int level = i + 1;
				long num = Long.parseLong(value.substring(0, value.length() - 1));
				long delayTimeMillis = tu * num;
				delayLevelTable.put(level, delayTimeMillis);
			}
		} catch (Exception e) {
			return false;
		}

		return true;
	}

    public static void compareAndSetMax(final AtomicLong target, final long value) {
        long prev = target.get();
        while (value > prev) {
            boolean updated = target.compareAndSet(prev, value);
            if (updated)
                break;

            prev = target.get();
        }
    }
}

class DelayStatsBenchmarkConsumer {
	// 1
	private final AtomicLong receiveMessageTotalCount = new AtomicLong(0L);
	// 2
	private final AtomicLong born2ConsumerTotalRT = new AtomicLong(0L);
	// 3
	private final AtomicLong store2ConsumerTotalRT = new AtomicLong(0L);
	// 4
	private final AtomicLong born2ConsumerMaxRT = new AtomicLong(0L);
	// 5
	private final AtomicLong store2ConsumerMaxRT = new AtomicLong(0L);
	// 6
	private final AtomicLong delayTotal = new AtomicLong(0L);

	public Long[] createSnapshot() {
		Long[] snap = new Long[] {//
		System.currentTimeMillis(),//
				this.receiveMessageTotalCount.get(),//
				this.born2ConsumerTotalRT.get(),//
				this.store2ConsumerTotalRT.get(),//
				this.born2ConsumerMaxRT.get(),//
				this.store2ConsumerMaxRT.get(), //
				this.delayTotal.get() //
		};

		return snap;
	}

	public AtomicLong getReceiveMessageTotalCount() {
		return receiveMessageTotalCount;
	}

	public AtomicLong getBorn2ConsumerTotalRT() {
		return born2ConsumerTotalRT;
	}

	public AtomicLong getStore2ConsumerTotalRT() {
		return store2ConsumerTotalRT;
	}

	public AtomicLong getBorn2ConsumerMaxRT() {
		return born2ConsumerMaxRT;
	}

	public AtomicLong getStore2ConsumerMaxRT() {
		return store2ConsumerMaxRT;
	}

	public AtomicLong getDelayTotal() {
		return delayTotal;
	}

}
